import useNotamStore from "@/store/notam.js";
import dayjs from "dayjs";

const notamStore = useNotamStore();

export default function () {
  let day = dayjs();
  let data = closureFilter();
  if (data.length == 0) {
    day = day.add(1, "day");
    data = closureFilter(day.format("YYYY-MM-DD HH:mm:ss"));
  }
  return {
    date: day.format("YYYY-MM-DD HH:mm:ss"),
    data: data,
  };
}

const closureFilter = (date = "") => {
  let target = date == "" ? dayjs() : dayjs(date);
  let targetString = target.format("YYYY-MM-DD HH:mm:ss");
  let closure = new Array();
  for (let i = 0; i < notamStore.count; i++) {
    let matched = false;
    let matchedStart = "";
    let matchedEnd = "";
    let notam = notamStore.content[i];
    let airport = notam.airport;
    let text = notam.text;
    let code = notam.number;
    let itemE = notam.origion.ITEME;
    if (
      itemE.includes("RWY") &&
      itemE.includes("关") &&
      !itemE.includes("滑")
    ) {
      if (notam.timeSlots && notam.timeSlots.length > 0) {
        for (let j = 0; j < notam.timeSlots.length; j++) {
          let slot = notam.timeSlots[j];
          let start = slot.start;
          let end = slot.end;
          let slotObj = dayjs(start);
          if (
            target.format("YYYYMMDD") == slotObj.format("YYYYMMDD") &&
            target.isBefore(end)
          ) {
            matched = true;
            matchedStart = start;
            matchedEnd = end;
          }
        }
      } else {
        let effectiveObj = dayjs(notam.effectiveTime);
        if (
          target.format("YYYYMMDD") == effectiveObj.format("YYYYMMDD") &&
          target.isBefore(notam.expirationTime)
        ) {
          matched = true;
          matchedStart = notam.effectiveTime;
          matchedEnd = notam.expirationTime;
        }
      }
      if (matched) {
        // console.log(notam.text);
        let start = matchedStart;
        let end = matchedEnd;
        let runways = new Array();
        if (airport == "ZUUU") {
          if (itemE.includes("02L") || itemE.includes("20R")) {
            runways.push("02L/20R");
          } else if (itemE.includes("02R") || itemE.includes("20L")) {
            runways.push("02R/20L");
          }
        } else if (airport == "ZUTF") {
          if (itemE.includes("02") || itemE.includes("20")) {
            runways.push("02/20");
          } else if (itemE.includes("01") || itemE.includes("19")) {
            runways.push("01/19");
          } else if (itemE.includes("11") || itemE.includes("29")) {
            runways.push("11");
          }
        } else if (airport == "ZUMY") {
          if (itemE.includes("32") || itemE.includes("14")) {
            runways.push("14/32");
          }
        }
        closure.push({ airport, start, end, runways, text, code });
      }
    }
  }
  closure.sort((a, b) => a.airport.localeCompare(b.airport));
  // console.log("RWY Closure: ", targetString, closure);
  return closure;
};
